<?php

  function rateComment($comment_id, $up) {
    $return_string = "";
    $temp = explode("_", $comment_id);
    $comment_id = $temp[1];
    if (!isset($_SESSION['user_name'])) {
      $return_string .= "<returncode>0</returncode>\n";
      $return_string .= "<errormessage>You're not logged in!</errormessage>\n";
      return $return_string;
    }
   
    $query = "SELECT * FROM Comment WHERE id=$comment_id";
    $result = mysql_query($query);
    if (mysql_num_rows($result) == 0) {
      $return_string .= "<returncode>0</returncode>\n";
      $return_string .= "<errormessage>No such comment</errormessage>\n";
      return $return_string;
    }
    $user_id = $_SESSION['user_id'];
      
    $query = "SELECT * FROM CommentRating "
           . "WHERE comment_id=$comment_id AND user_id=$user_id"; 
    $result = mysql_query($query);

    $rating = $up == 'true' ? 1 : -1;

    if (mysql_num_rows($result) == 0) {
      $query = "INSERT INTO CommentRating (comment_id, user_id, rating) "
             . "VALUES($comment_id, $user_id, $rating)";
      $result = mysql_query($query);
    } else {
      $query = "UPDATE CommentRating "
             . "SET rating=$rating "
             . "WHERE comment_id=$comment_id AND user_id=$user_id";
      $result = mysql_query($query);
    }
    $return_string .= "<returncode>1</returncode>";
    return $return_string;
  }
?>
